package com.znufe.exam.controller.admin;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.github.pagehelper.PageInfo;
import com.znufe.exam.base.BaseApiController;
import com.znufe.exam.configuration.config.annotation.Log;
import com.znufe.exam.configuration.config.enums.BusinessType;
import com.znufe.exam.service.LecturerService;
import com.znufe.exam.utility.PageInfoHelper;
import com.znufe.exam.viewmodel.admin.lecturertitle.LecturerTitleCreateVm;
import com.znufe.exam.viewmodel.admin.lecturertitle.LecturerTitlePageRequestVm;
import com.znufe.exam.viewmodel.admin.lecturertitle.LecturerTitlePageResponseVm;
import com.znufe.exam.viewmodel.admin.lecturertitle.LecturerTitleResponseVm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import com.znufe.exam.domain.LecturerTitle;
import com.znufe.exam.service.LecturerTitleService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.znufe.exam.base.RestResponse;
import com.znufe.exam.base.SystemCode;

import javax.validation.Valid;

/**   
 * 
 * @Description:  讲师职称分类表接口层
 * @Author:          
 * @CreateDate:   Course
 * @Version:      V1.0
 *    
 */
@Api(description = "讲师职称分类表",value="讲师职称分类表" )
@RestController
@RequestMapping("/api/admin/lecturer/title")
public class LecturerTitleController extends BaseApiController {

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	public LecturerTitleService lecturerTitleService;

    @Autowired
    public LecturerService lecturerService;


	@PreAuthorize("@ss.hasPermi('category:lecturetitle:edit')")
    @Log(title = "讲师职称管理",businessType = BusinessType.UPDATE)
	@RequestMapping(value = "/changeStatus/{id}",method = RequestMethod.GET)
    @ApiOperation(value = "管理端：修改讲师职称类别状态")
    public RestResponse<Integer> changeStatus(@PathVariable Integer id){
	    try{
	        LecturerTitle title = lecturerTitleService.selectByPrimaryKey(id);
	        if (title != null){
	            Integer newStatus = title.getStatus() == 1 ? 0 : 1;
	            title.setStatus(newStatus);
	            title.setGmtModified(new Date());
	            int reg = lecturerTitleService.updateByPrimaryKeySelective(title);
	            if (reg > 0){
	                return RestResponse.ok(newStatus);
                }else {
	                return RestResponse.fail(SystemCode.UpdateDataFail.getCode(), SystemCode.UpdateDataFail.getMessage());
                }
            }else {
                return RestResponse.fail(SystemCode.NoDataExist.getCode(), SystemCode.NoDataExist.getMessage());
            }
        }catch (Exception e){
            return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
        }
    }

    @PreAuthorize("@ss.hasPermi('category:lecturetitle:list')")
    @RequestMapping(value = "/titlePage",method = RequestMethod.POST)
    @ApiOperation(value = "管理端：分页展示讲师职称分类信息+搜索")
    public RestResponse<PageInfo<LecturerTitlePageResponseVm>> titlePage(@RequestBody LecturerTitlePageRequestVm requestVm){
	    try {
	        requestVm.setTitleName(requestVm.getTitleName().trim());
	        PageInfo<LecturerTitle> pageInfo = lecturerTitleService.titlePage(requestVm);
	        PageInfo<LecturerTitlePageResponseVm> page = PageInfoHelper.copyMap(pageInfo,d->LecturerTitlePageResponseVm.from(d));
	        return RestResponse.ok(page);
        }catch (Exception e){
	        return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
        }
    }

    @PreAuthorize("@ss.hasPermi('category:lecturetitle:remove')")
    @Log(title = "讲师职称管理",businessType = BusinessType.DELETE)
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.GET)
    @ApiOperation(value = "管理端：通过ID删除职称")
    public RestResponse<Integer> delete(@PathVariable Integer id){
	    try {
	        LecturerTitle title = lecturerTitleService.selectByPrimaryKey(id);
	        if (title != null){
	            title.setIsDeleted(1);
	            lecturerTitleService.updateByPrimaryKeySelective(title);
	            //删除该职称所有讲师
                lecturerService.deleteAllLecturerByTitle(id);
	            return RestResponse.ok(1);
            }else {
	            return RestResponse.fail(SystemCode.DeleteDataFail.getCode(),SystemCode.DeleteDataFail.getMessage());
            }
        }catch (Exception e){
	        return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
        }
    }

    @PreAuthorize("@ss.hasPermi('category:lecturetitle:edit')")
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ApiOperation(value = "管理端：新建职称与修改职称信息",
                  notes = "新增/更新职称信息（更新请传入职称id）")
    public RestResponse<LecturerTitle> edit(@RequestBody @Valid LecturerTitleCreateVm createVm){
	    if (createVm.getId() == null){
	        LecturerTitle existTitle = lecturerTitleService.getTitleByName(createVm.getTitleName());
	        if (null != existTitle){
	            return new RestResponse<>(421,"职称已存在");
            }
        }
        LecturerTitle newTitle = modelMapper.map(createVm,LecturerTitle.class);
	    if (createVm.getId() == null){
	        newTitle.setGmtCreate(new Date());
	        newTitle.setIsDeleted(0);
	        newTitle.setStatus(0);
	        lecturerTitleService.insertSelective(newTitle);
        }else {
	        newTitle.setGmtModified(new Date());
	        lecturerTitleService.updateByPrimaryKeySelective(newTitle);
        }
        return RestResponse.ok(newTitle);
    }

    @PreAuthorize("@ss.hasPermi('category:lecturetitle:query')")
	@RequestMapping(value = "/select/{id}",method = RequestMethod.GET)
	@ApiOperation(value = "管理端：点击编辑职称", notes = "根据ID获取讲师职称信息")
	public RestResponse<LecturerTitle> getLecturerTitleById(@PathVariable("id")Integer id){
		try {
			LecturerTitle lecturerTitle=lecturerTitleService.selectByPrimaryKey(id);
			if (lecturerTitle!=null) {
				return RestResponse.ok(lecturerTitle);
			} else {
				logger.error("查询讲师职称分类表执行失败："+lecturerTitle.toString());
				return RestResponse.fail(SystemCode.NoDataExist.getCode(),SystemCode.NoDataExist.getMessage());
			}
		} catch (Exception e) {
			logger.error("查询讲师职称分类表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}

	@RequestMapping(value = "/getAllTitle",method = RequestMethod.GET)
    @ApiOperation(value = "管理端：获取所有职称")
    public RestResponse<List<LecturerTitleResponseVm>> getAllTitle(){
        List<LecturerTitle> titleList = lecturerTitleService.getAllTitle();
        List<LecturerTitleResponseVm> responseVmList = titleList.stream().map(d -> {
            LecturerTitleResponseVm vm = modelMapper.map(d,LecturerTitleResponseVm.class);
            return vm;
        }).collect(Collectors.toList());
        return RestResponse.ok(responseVmList);
    }
}